<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="550px"
        :clickModalClose="true"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
        <el-form-item label="站点名称" prop="siteName">
          <el-input v-model="formData.siteName" placeholder="请输入站点名称" :disabled="isDisabled('siteName')"/>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="formData.deviceName" placeholder="请输入设备名称" :disabled="isDisabled('deviceName')"/>
        </el-form-item>
        <el-form-item label="上报时间" prop="reportingTime">
          <el-date-picker
              class="flex-1 !flex"
              v-model="formData.reportingTime"
              type="datetime"
              clearable
              value-format="YYYY-MM-DD hh:mm:ss"
              placeholder="请选择上报时间"
              :disabled="isDisabled('reportingTime')"
          />
        </el-form-item>
        <el-form-item label="管理员" prop="administrator">
          <el-input v-model="formData.administrator" placeholder="请输入管理员" :disabled="isDisabled('administrator')"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="formData.contactNumber" placeholder="请输入联系电话" :disabled="isDisabled('contactNumber')"/>
        </el-form-item>
        <el-form-item label="详情描述" prop="details">
          <div class="input-div">
            <el-input type="textarea" :rows="4" v-model="formData.details" placeholder="请输入详情描述"
                      :disabled="isDisabled('details')"/>
          </div>
        </el-form-item>
        <el-form-item label="详情图" prop="detailChart">
          <div class="image-div">
            <img v-for="(image, index) in detailImages"
                 :key="image"
                 :src="image"
                 class="imagedetail"
                 @click="handlePreview(index)"/>
          </div>
        </el-form-item>
        <el-form-item label="处理结果" prop="processingDetail">
          <el-input type="textarea" :rows="4" v-model="formData.processingDetail" placeholder="请输入处理详情"
                    :disabled="isDisabled('processingDetail')"/>
        </el-form-item>
		<el-form-item label="处理详情图" prop="fieldDrawing">
		  <div class="image-div">
		    <img v-for="(image, index) in formData.fieldDrawing"
		         :key="index"
		         :src="image"
		         class="imagedetail"
		         @click="handlePreview(index)"/>
		  </div>
		  <el-upload
		      ref="uploadRef"
		      class="upload-demo"
		      :action="uploadUrl"
		      :headers="headers"
		      :on-success="handleSceneUploadSuccess"
		      :show-file-list="false"
		  >
		    <el-button type="primary">点击上传</el-button>
		  </el-upload>
		</el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type {FormInstance} from 'element-plus'
import {recordEdit, recordAdd, recordDetail} from '@/api/record'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type {PropType} from 'vue'
import Viewer from 'viewerjs';

import 'viewerjs/dist/viewer.css'
import {getToken} from "@/utils/auth";
import config from "@/config";

const uploadUrl = ref(config.baseUrl+'api/upload/image');

const token = getToken()
const headers = ref({token});


defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑运维/事件上报' : '新增运维/事件上报'
})

const formData = reactive({
  omId: '',
  siteName: '',
  deviceName: '',
  reportingTime: '',
  administrator: '',
  contactNumber: '',
  details: '',
  detailChart: '',
  type: '',
  processingDetail: '',
  omStatus: '',
  processingTime: '',
  completionTime: '',
  founder: '',
  creationTime: '',
  modifier: '',
  fieldDrawing:[]
})

const formRules = {
  omId: [
    {
      message: '请输入运维编号',
      trigger: ['blur']
    }
  ],
  processingDetail: [
    {
      required: true,
      message: '请输入处理详情',
      trigger: ['blur']
    }
  ],
  fieldDrawing: [
    {
      required: true,
      message: '请上传现场图片',
      trigger: 'change'
    }
  ]
}
//上传现场图片
const handleSceneUploadSuccess = (response: any, file: any, fileList: any) => {
  console.log(response.data.path,"上传的图片")
  // 处理上传成功的回调函数
  const imageUrl = response.data.path; // 根据实际接口返回的字段名修改
  formData.fieldDrawing.push(imageUrl); // 将新的图片路径 push 到数组中
  console.log(formData.fieldDrawing,"存起来的图片路径")
}
// 计算是否禁用字段
const isDisabled = (fieldName: string) => {
  return mode.value === 'edit' && fieldName !== 'processingDetail';
};

const handleSubmit = async () => {
  await formRef.value?.validate()
  const data: any = {...formData}
  mode.value == 'edit' ? await recordEdit(data) : await recordAdd(data)
  popupRef.value?.close()
  feedback.msgSuccess('操作成功')
  emit('success')
}

const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
}

const getDetail = async (row: Record<string, any>) => {
  const data = await recordDetail({
    id: row.omId
  })
  setFormData(data)
}

const handleClose = () => {
  emit('close')
}

const detailImages = computed(() => {
  return formData.detailChart.split(',').map(image => image.trim()).filter(image => image !== '');
});

const currentIndex = ref(-1);

let viewerRef = ref(null)

const handlePreview = (index: number) => {
  currentIndex.value = index;
  viewerRef.value = new Viewer(document.querySelectorAll('.imagedetail')[index], {
    toolbar: false, // 如果需要显示工具栏，则设置为true
    navbar: false, // 如果需要显示导航栏，则设置为true
    title: false // 如果需要显示图片标题，则设置为true
  })
  viewerRef.value.show();
};

import {onBeforeUnmount} from 'vue';

onBeforeUnmount(() => {
  if (viewerRef.value) {
    viewerRef.value.destroy();
  }
});

defineExpose({
  open,
  setFormData,
  getDetail,
  handlePreview,
})
</script>
<style>
.imagedetail {
  width: 100px;
  height: 100px;
  margin-top: 10px;
  cursor: pointer;
}

.image-div {
  display: flex;
  flex-flow: wrap;
}

.viewer-container {
  z-index: 9999 !important;
}

.input-div {
  width: 100%;
}

.input-div .el-textarea__inner {
  height: auto;
  min-height: 120px;
}

.el-textarea__inner::-webkit-scrollbar {
  width: 0;
}

.el-textarea__inner {
  overflow-y: scroll;
}
</style>
